import uuid
import const
import xlrd
import sys
import pathlib
import time
import re
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.profile import region_provider
from aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest

try:
    reload(sys)
    sys.setdefaultencoding('utf8')
except NameError:
    pass
except Exception as err:
    raise err

# 注意：不要更改
REGION = "cn-hangzhou"
PRODUCT_NAME = "Dysmsapi"
DOMAIN = "dysmsapi.aliyuncs.com"

acs_client = AcsClient(const.ACCESS_KEY_ID, const.ACCESS_KEY_SECRET, REGION)
region_provider.add_endpoint(PRODUCT_NAME, REGION, DOMAIN)

# excel文件默认路径
EXCEL_FILE_PATH = "E:\\ProjectCodeLib\\"
# 短信标签
SIGN_NAME = "衣当先"
# 短信模板码
TEMPLATE_CODE = "SMS_150579449"


def send_sms(business_id, phone_numbers, sign_name, template_code, template_param=None):
    smsRequest = SendSmsRequest.SendSmsRequest()
    # 申请的短信模板编码,必填
    smsRequest.set_TemplateCode(template_code)

    # 短信模板变量参数
    if template_param is not None:
        smsRequest.set_TemplateParam(template_param)

    # 设置业务请求流水号，必填。
    smsRequest.set_OutId(business_id)

    # 短信签名
    smsRequest.set_SignName(sign_name)

    # 短信发送的号码列表，必填。
    smsRequest.set_PhoneNumbers(phone_numbers)

    # 调用短信发送接口，返回json
    smsResponse = acs_client.do_action_with_exception(smsRequest)

    # TODO 业务处理

    return smsResponse


def send_group_message(excel_file_name):
    pattern = "^(10[0-9]|11[0-9]|12[0-9]|13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])\\d{8}$"
    file_path = "%s%s" % (EXCEL_FILE_PATH, excel_file_name)
    path = pathlib.Path(file_path)
    if not path.exists():
        print("The %s is not exist")

    execl_file = xlrd.open_workbook(file_path)
    excel_sheet = execl_file.sheets()[0]

    norows = excel_sheet.nrows
    for i in range(norows):

        user_msg_list = excel_sheet.row_values(i)
        user_phone = str(user_msg_list[-1])
        # 从excel中读取的出手机号是单精度浮点，需要格式处理
        if "." in user_phone:
            user_phone = user_phone.split(".")[0]

        if re.match(pattern, user_phone):
            print("phone number: %s" % user_phone)
            business_id = uuid.uuid1()
            print(send_sms(business_id, user_phone, SIGN_NAME, TEMPLATE_CODE))
            time.sleep(2)


if __name__ == '__main__':
    file_name = sys.argv[1]
    send_group_message(file_name)
